<?php if (! defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
class Login extends CI_Controller {
	
	public function __construct() {
		parent::__construct ();
		$this->load->model ( 'users', '', TRUE );
	}
	
	public function index() {
		// This method will have the credentials validation
		$this->load->library ( 'form_validation' );
		
		$this->form_validation->set_rules ( 'email', 'E-mail', 'trim|required|xss_clean' );
		$this->form_validation->set_rules ( 'pass', 'Password', 'trim|required|xss_clean|callback_check_database' );
		
		if ($this->form_validation->run () == FALSE) {
			// Go to login error page
			/*$this->load->helper('language');
			$data['page'] = 'pages/pt/whoweare';
			$data['message'] = 'Invalid username or password';
			$this->load->view ('mainview', $data);*/
			echo '<div class="alert alert-danger">O login ou a senha informados estão incorretos!</div>';
		} else {
			// Go to private area
			//redirect ( '', 'refresh' );
			echo 'ok';
		}
	}
	
	public function check_database($password) {
		// Field validation succeeded.&nbsp; Validate against database
		$email = $this->input->post ('email');
		
		// query the database
		$result = $this->users->login ($email, $password);
		if ($result) {
			$sess_array = array ();
			foreach ( $result as $row ) {
				$lang = $row->nm_country;
				if($lang == 'Brasil'){
					$lang = 'pt';
				}elseif ($lang == 'USA'){
					$lang = 'en';
				}elseif ($lang == 'Spain'){
					$lang = 'es';
				}
				$sess_array = array (
					'id'		=> $row->id_user,
					'username' 	=> $row->nm_user,
					'email' 	=> $row->nm_email,
					'language'  => $lang,
					'loggedin'	=> TRUE					
				);
				$this->session->set_userdata ($sess_array);
			}
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function logout() {
		$this->session->sess_destroy();
		redirect ( '', 'refresh' );
	}
}
?>
